import os
import re
import shutil
import subprocess
import zipfile

import requests

from common.tools import get_driver_path, get_project_path


class ChromeDriverManager:
    def __init__(self):
        self.download_dir = os.path.dirname(get_driver_path("chromedriver"))
        self.driver_path = get_driver_path("chromedriver")
        self.url = "https://registry.npmmirror.com/-/binary/chrome-for-testing/"

    def get_chrome_version(self):
        """获取已安装的 Chrome 浏览器版本"""
        chrome_path = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
        result = subprocess.run([chrome_path, "--version"],
                                capture_output=True, text=True, check=True)
        version_output = result.stdout.strip()
        version_match = re.search(r'(\d+\.\d+\.\d+\.\d+)', version_output)
        return version_match.group(1)

    def get_installed_driver_version(self):
        """获取已安装的 ChromeDriver 版本"""
        if not os.path.exists(self.driver_path):
            return None
        os.chmod(self.driver_path, 0o755)
        result = subprocess.run([self.driver_path, "--version"],
                                capture_output=True, text=True, check=True)
        version_output = result.stdout.strip()
        version_match = re.search(r'(\d+\.\d+\.\d+\.\d+)', version_output)
        return version_match.group(1)

    def is_compatible_version(self, chrome_version, driver_version):
        """检查版本是否兼容（只需要主版本号匹配）"""
        return chrome_version.split('.')[0] == driver_version.split('.')[0]

    def get_platform_specific_urls(self, major_version):
        """获取特定平台的Chrome for Testing URLs"""
        # 使用sysctl来检测实际硬件架构
        result = subprocess.run(['sysctl', '-n', 'hw.optional.arm64'],
                                capture_output=True, text=True)
        if result.returncode == 0 and result.stdout.strip() == '1':
            target_platform = "mac-arm64"
        else:
            target_platform = "mac-x64"
        # 获取基础版本URL
        response = requests.get(self.url)
        escaped_version = re.escape(major_version)
        pattern = re.compile(rf"^{escaped_version}(\.\d+)*/$")
        base_urls = [item["url"] for item in response.json() if
                     item.get("type") == "dir" and pattern.match(item.get("name", ""))]
        # 添加平台路径
        url_list = []
        for base_url in base_urls:
            response = requests.get(base_url + f'{target_platform}/')
            for item in response.json():
                if "chromedriver" in item["name"]:
                    url_list.append(item["url"])

        return url_list

    def install(self):
        """
        安装 ChromeDriver
        :param download_url: ChromeDriver 的下载地址
        :return: ChromeDriver 的路径
        """
        # 获取 Chrome 版本
        chrome_version = self.get_chrome_version()
        if not chrome_version:
            raise Exception("无法获取 Chrome 版本，请确保 Chrome 已安装")
        print(f"检测到 Chrome 版本: {chrome_version}")
        # 检查是否已安装兼容的 ChromeDriver
        driver_version = self.get_installed_driver_version()
        if driver_version and self.is_compatible_version(chrome_version, driver_version):
            print(f"已存在兼容的 ChromeDriver 版本: {driver_version}")
            return os.path.join(self.driver_path)
        # 删除旧版本
        if os.path.exists(self.driver_path):
            os.remove(self.driver_path)
        # 从URL中提取文件名并确定解压文件夹名
        download_url = self.get_platform_specific_urls(chrome_version.split('.')[0])[0]
        zip_filename = download_url.split('/')[-1]
        extracted_folder = zip_filename.replace('.zip', '')

        # 下载文件
        print("开始下载 ChromeDriver...")
        zip_path = os.path.join(self.download_dir, zip_filename)
        response = requests.get(download_url)
        if not os.path.exists(get_project_path() + '/drivers'):
            os.makedirs(get_project_path() + '/drivers')
        with open(zip_path, 'wb') as f:
            f.write(response.content)
        print("下载完成")

        # 解压文件
        print("正在解压...")
        with zipfile.ZipFile(zip_path, 'r') as zip_ref:
            zip_ref.extractall(self.download_dir)

        # 从解压文件夹中移动 chromedriver（使用os.rename）
        chromedriver_src = os.path.join(self.download_dir, extracted_folder, "chromedriver")

        # 使用 os.rename 移动文件
        os.rename(chromedriver_src, self.driver_path)

        # 设置执行权限
        os.chmod(self.driver_path, 0o755)

        # 清理文件：删除压缩包和解压文件夹
        os.remove(zip_path)
        shutil.rmtree(os.path.join(self.download_dir, extracted_folder))

        print(f"ChromeDriver 已安装到: {self.driver_path}")
        return self.driver_path


# 使用示例
if __name__ == "__main__":
    manager = ChromeDriverManager()
    print(manager.get_platform_specific_urls("140"))
    try:
        driver_path = manager.install()
        print(f"ChromeDriver 路径: {driver_path}")
    except Exception as e:
        print(f"安装失败: {e}")
